package com.graduation.user.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.common.exception.ManageException;
import com.graduation.common.result.R;
import com.graduation.common.utils.JwtHelper;
import com.graduation.common.utils.MD5;
import com.graduation.model.entity.Administrator;
import com.graduation.model.entity.Teacher;
import com.graduation.model.vo.ExcelContentVo;
import com.graduation.model.vo.SchoolInfoVo;
import com.graduation.model.vo.StudentExVo;
import com.graduation.model.vo.TeacherQueryVo;
import com.graduation.user.listener.MyAddStuListener;
import com.graduation.user.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tianwenle
 * @since 2022-11-16
 */
@RestController
@RequestMapping("/admin/user/teacher")
public class TeacherController {


    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R teacherLogin(@RequestBody Teacher teacher) throws UnsupportedEncodingException {
        String username = teacher.getUsername();
        String password = teacher.getPassword();

        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", username);
        wrapper.eq("password", MD5.encrypt(password));
        Teacher teacher1 = teacherService.getOne(wrapper);

        if (teacher1 == null) {
            throw new ManageException("账号密码错误！");
        }

        // 生成token
        String token = JwtHelper.createToken(teacher1.getLoginNo(), teacher1.getUsername(), "teacher");

        redisTemplate.opsForValue().set("user",teacher1.getUsername());

        return R.ok().data("token", token);
    }

    /**
     * 编写info接口
     */
    @GetMapping("/info")
    public R infoShow(String token) throws UnsupportedEncodingException {
        // 解析token 获取登录的用户名
        String loginNo = JwtHelper.getLoginNo(token);

        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);
        return R.ok().data("roles", Arrays.asList("admin")).data("introduction", "老师")
                .data("avatar", teacher.getHeadUrl())
                .data("name", teacher.getNickName());
    }

    /**
     * 根据id查询教师信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getById/{id}")
    public R getTeacherById(@PathVariable("id") Long id) {
        Teacher teacher = teacherService.getTeacherInfoById(id);
        return R.ok().data("teacher", teacher);
    }


    @GetMapping("/getTeacherInfoByTeacherId/{id}")
    public Teacher getTeacherInfoByTeacherId(@PathVariable("id") Long id) {
        return teacherService.getById(id);
    }

    @GetMapping("getNameById/{id}")
    public String getTeacherNameById(@PathVariable("id") Long id) {
        Teacher teacher = teacherService.getTeacherInfoById(id);
        return teacher.getUsername();
    }

    /**
     * 查询所有老师的信息
     *
     * @return
     */
    @GetMapping("/list")
    public R getList() {
        List<Teacher> list = teacherService.getTeacherList();
        return R.ok().data("list", list);
    }

    /**
     * 修改老师的信息
     */
    @PutMapping("/update")
    public R update(@RequestBody Teacher teacher) {
        teacherService.updateById(teacher);
        return R.ok();
    }

    /*
       删除老师信息
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id) {
        teacherService.removeById(id);
        return R.ok();
    }

    /**
     * 添改教师信息
     */
    @PostMapping("/add")
    public R addTeacher(@RequestBody Teacher teacher) {
        teacherService.saveOrUpdate(teacher);
        return R.ok();
    }

    /**
     * 分页查询
     */
    @GetMapping("/page/{pageSize}/{limit}")
    public R teacherPage(@PathVariable Integer pageSize, @PathVariable Integer limit, TeacherQueryVo teacherQueryVo) {
        Map<String, Object> map = teacherService.teacherPage(pageSize, limit, teacherQueryVo);
        return R.ok().data(map);
    }

    @GetMapping("/getTeacherInfo")
    public R getTeacherInfo() {
        List<SchoolInfoVo> list = teacherService.getTeacherInfo();
        return R.ok().data("list", list);
    }

    @GetMapping("/getByUsername")
    public R getByUsername(HttpServletRequest request) throws UnsupportedEncodingException {
        String token = request.getHeader("X-Token");

        String loginNo = JwtHelper.getLoginNo(token);

        if (loginNo == null) {
            throw new ManageException("登录失效，请重新登录！");
        }
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();

        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);
        return R.ok().data("teacher", teacher);
    }

    @GetMapping("/getStatus/{loginNo}")
    public Boolean getStatus(@PathVariable String loginNo) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);
        if (teacher == null) {
            throw new ManageException("非法操作");
        }
        return true;
    }


    @GetMapping("/getTeacherIdByLoginNo/{loginNo}")
    public Long getTeacherIdByUsername(@PathVariable String loginNo) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);
        if (teacher == null) {
            return null;
        }
        return teacher.getId();
    }


    @PostMapping("/batchAddStudent")
    public R batchAddStudent(MultipartFile file,
                             HttpServletRequest request,
                             Teacher teacher
    ) throws IOException {

        ExcelContentVo excelContentVo = new ExcelContentVo();
        excelContentVo.setTeacherId(teacher.getId());
        excelContentVo.setDepartmentId(teacher.getDepartmentId());

        teacherService.batchAddStudents(file, excelContentVo);

        return R.ok();
    }


}

